package com.rongc.client.freight.base.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.rongc.client.core.exception.RegexException;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.CountDownUtil;
import com.rongc.client.core.utils.LogUtils;
import com.rongc.client.core.utils.RegexUtil;
import com.rongc.client.core.utils.SPUtil;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.request.api.LoginApi;
import com.rongc.client.freight.base.request.api.RegisterCodeApi;
import com.rongc.client.freight.base.request.result.NullResult;
import com.rongc.client.freight.base.request.result.UserResult;
import com.rongc.client.freight.base.view.widget.PhoneNumberTextWatcher;
import com.rongc.client.freight.service.DicSyncService;
import com.rongc.client.freight.utils.UserUtils;
import com.rongc.client.freight.utils.UtilMethod;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by ccqx on 2017/6/27.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener{
    @Bind(R.id.et_mobile)
    EditText mEtMobile;
    @Bind(R.id.et_verifiy)
    EditText mEtVerifiy;
    @Bind(R.id.et_invite)
    EditText mEtInvite;
    @Bind(R.id.tv_verifiy)
    TextView mTvVerifiy;
    @Bind(R.id.tv_protocol)
    TextView mTvProtocol;

    CountDownUtil countDownUtil;

    @OnClick({R.id.btn_login,R.id.tv_verifiy,R.id.tv_protocol})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_login:
                /*UserUtils.mockUser();
                ActivityUtils.startActivity(this,HostActivity.class);
                finish();*/
                try{
                    prepare();
                    RequestManager.getInstance().call(new LoginApi(
                            new LoginApi.LoginParams(mEtMobile.getText().toString().replace(" ",""),
                            mEtVerifiy.getText().toString(),mEtInvite.getText().toString()),
                            respOrderListener, errorListener));
                }catch (RegexException e){
                    ActivityUtils.toast(e.getMessage());
                }
                break;
            case R.id.tv_verifiy:
                try{
                    prepareCode();
                    UtilMethod.showProgressDialog(this);
                    mTvVerifiy.setEnabled(false);
                    RequestManager.getInstance().call(new RegisterCodeApi(new RegisterCodeApi.RegisterCodeParams(
                            mEtMobile.getText().toString().replace(" ","")),
                            respCodeListener, errorListener));
                }catch (RegexException e){
                    ActivityUtils.toast(e.getMessage());
                }
                break;
            case R.id.tv_protocol:
                Bundle bundle = new Bundle();
                bundle.putString("type","reg");
                ActivityUtils.startActivity(this,WebActivity.class,bundle);
                break;
        }
    }

    void prepare() throws RegexException {
        if(!RegexUtil.isPhone(mEtMobile.getText().toString().replace(" ",""))){
//            mEtMobile.setError("请输入正确的手机号");
            throw new RegexException("请输入正确的手机号");
        }else if(!RegexUtil.checkNotNull(mEtVerifiy.getText().toString())){
//            mEtVerifiy.setError("请输入验证码");
            throw new RegexException("请输入验证码");
        }

    }

    void prepareCode() throws RegexException {
        if(!RegexUtil.isPhone(mEtMobile.getText().toString().replace(" ",""))){
//            mEtMobile.setError("请输入正确的手机号");
            throw new RegexException("请输入正确的手机号");
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mTvVerifiy.setEnabled(false);
                    mTvVerifiy.setText(String.format(getResources().getString(R.string.login_verifiy_reciprocal),
                            (countDownUtil.getDuration(CountDownUtil.VERIFIY_TYPE) -
                                    countDownUtil.getCountDown(CountDownUtil.VERIFIY_TYPE))+""));
                    break;
                case 1:
                    mTvVerifiy.setEnabled(true);
                    mTvVerifiy.setText(R.string.login_verifiy_tip);
                    break;
                default:
                    break;
            }
        }
    };

    Response.Listener<NullResult> respCodeListener = new Response.Listener<NullResult>() {

        @Override
        public void onResponse(NullResult response) {

            if (HandleCode.requestSuccess()) {
                ActivityUtils.toast("验证码已发送");
                new Thread(countDownUtil.getRunnable(CountDownUtil.VERIFIY_TYPE)).start();
            } else {
                mTvVerifiy.post(new Runnable() {
                    @Override
                    public void run() {
                        mTvVerifiy.setEnabled(true);
                    }
                });
            }
            UtilMethod.dismissProgressDialog(LoginActivity.this);
        }
    };


    Response.Listener<UserResult> respOrderListener = new Response.Listener<UserResult>() {

        @Override
        public void onResponse(UserResult response) {
            if (HandleCode.requestSuccess()) {
                UserUtils.makeUser(response);
                SPUtil.putString("phone",mEtMobile.getText().toString().replace(" ",""));
                ActivityUtils.toast("登录成功");
                ActivityUtils.startActivity(LoginActivity.this, HostActivity.class);
                finish();
            } else {
                UtilMethod.dismissProgressDialog(LoginActivity.this);
            }
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            LogUtils.i("error.getMessage(): " + error.getMessage());
            UtilMethod.dismissProgressDialog(LoginActivity.this);
        }
    };

    @Override
    public void initView() {
        Intent intent = new Intent(LoginActivity.this, DicSyncService.class);
        startService(intent);

        if(UniApplication.getInstance().hasLogin()){
            ActivityUtils.startActivity(this,HostActivity.class);
            finish();
        }else{
            countDownUtil = CountDownUtil.getInstance();
            countDownUtil.initRunnable(handler,CountDownUtil.VERIFIY_TYPE);
            if(countDownUtil.getCountDown(CountDownUtil.VERIFIY_TYPE) != 0){
                mTvVerifiy.setEnabled(false);
                mTvVerifiy.setText(String.format(getResources().getString(R.string.login_verifiy_reciprocal),
                        (countDownUtil.getDuration(CountDownUtil.VERIFIY_TYPE) -
                                countDownUtil.getCountDown(CountDownUtil.VERIFIY_TYPE))+""));
                new Thread(countDownUtil.getRunnable(CountDownUtil.VERIFIY_TYPE)).start();
            }
            setStatusColor();

            new PhoneNumberTextWatcher(mEtMobile);
        }

        String phone = SPUtil.getString("phone");
        mEtMobile.setText(phone);
        mTvProtocol.setText(Html.fromHtml(getResources().getString(R.string.login_protocol_lable)));

    }



    @Override
    public int getLayoutId() {
        return R.layout.activity_sys_login;
    }
}
